package com.tensquare.user.interceptor;

import cn.hutool.core.util.StrUtil;
import com.tensquare.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zzb
 * @create 2021/2/23
 * Jwt拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //得到请求头
        String header = request.getHeader("Authorization");
        //判断是否存在
        if (StrUtil.isNotBlank(header) && header.startsWith("Bearer ")){
            //从第七个位置截取
            String token = header.substring(7);//得到token信息
            //解析token
            Claims claims = jwtUtil.parseJwt(token);
            //判断是否有值
            if(claims != null){
                request.setAttribute("claims",claims);

            }
        }
        return true;
    }
}
